/** Globals **/
var participantData;
var demonstrationsData;
var participant;
var id;
var baseIconDemonstration;
var baseIconParticipant;


/* void */ function $(/* String */ id) {
  return document.getElementById(id);
}


/* void */ function initIcons(){
  // Create a base icon for the marker of the demonstration that specifies the
  // shadow, icon dimensions, etc.
  baseIconDemonstration = new GIcon();
  baseIconDemonstration.shadow = "http://www.google.com/mapfiles/shadow50.png";
  baseIconDemonstration.image = "crowdUp_picto_board.png";
  baseIconDemonstration.iconSize = new GSize(34, 53);
  baseIconDemonstration.shadowSize = new GSize(37, 34);
  baseIconDemonstration.iconAnchor = new GPoint(24, 53);
  baseIconDemonstration.infoWindowAnchor = new GPoint(24, 2);
  baseIconDemonstration.infoShadowAnchor = new GPoint(18, 25);

  // Create a base icon for the marker of a participant that specifies the
  // shadow, icon dimensions, etc.
  baseIconParticipant = new GIcon();
  baseIconParticipant.shadow = "http://www.google.com/mapfiles/shadow50.png";
  baseIconParticipant.image = "CrowdUp_pict_man.png";
  baseIconParticipant.iconSize = new GSize(21, 46);
  baseIconParticipant.shadowSize = new GSize(37, 34);
  baseIconParticipant.iconAnchor = new GPoint(10, 46);
  baseIconParticipant.infoWindowAnchor = new GPoint(12, 5);
  baseIconParticipant.infoShadowAnchor = new GPoint(18, 25);

}

/*
 * load the information
 * this function is called from the onload of the body
 */
/* void */ function start() {
  var map = document.getElementById('map');
  var gmap = new GMap(map);
  gmap.addControl(new GLargeMapControl);
  gmap.addControl(new GMapTypeControl);

  //initialize the icons for the demonstration and participants
  initIcons();

  //set the center to paris
  gmap.setCenter(new GLatLng(48.858853,2.347005), 12);

  //get the id if one of the demonstration
  id = /id=(\d+)/.exec(window.document.location.search);
  if (id) {
    id = id[1];
  }
  //read if the user already participate in this demonstration using the cookies
  participant = readCookie("demonstration_"+id);

  //check if we create a new demo
  var newDemo = /newdemo=(.*)/.exec(window.document.location.search);
  if (newDemo) {
    newDemo = newDemo[1];
  }
  
  if (newDemo) {
    //if it's a new demo, we display the start block with the form of the 
    $('start').style.display = ''; 
    startCreateDemonstration(gmap);
  } else if (!id) {
    //show the demonstration block in the html
    $('demonstrations').style.display = '';
    // load the informations about the demonstrations and display them
    loadDemonstrations(gmap);
  } else {
    // if the user does not already participate in the demonstration, we display it
    if (!participant) {
      $('newparticipant').style.display = '';
    }
    // display the block of the participant list
    $('participant').style.display = '';
    // load the informations about the demonstration and display them
    loadDemonstration(gmap, id);
  }
  // Translate the application
  translate(null);
}

/*
 * center the Gmap to paris
 * Add a dragable pointer to the set the starting point of the demonstration
 */
/* void */ function startCreateDemonstration(/* Gmap */ gmap) {
  // set the center to paris
  gmap.setCenter(new GLatLng(48.858853,2.347005), 12);
  // Add a dragable pointer to the set the starting point of the demonstration
  addPositionMarker(gmap, "savedemonstration");
}


/*
 * center the Gmap to paris
 * Add a dragable pointer to the set the starting point of the demonstration
 */
/* void */ function addPositionMarker(/* Gmap */ gmap, /* String */ form) {
  /* GMarker */ var mark = null;

  // add a click listener on the gmap 
  GEvent.addListener(gmap, "click", function(/* GMarker */ overlay, /* GLatLng */ point) {
    if (point) {
      // if we did not create a mark before, we add one
      if (!mark) {
        mark = new GMarker(point, {
          draggable: true
        });
        // we enable the dragging
        mark.enableDragging();
        // we add the marker to the map
        gmap.addOverlay(mark);
        // we set the postion to the clicked one
        formSetPosition(form, point);
        // we add a listener for the end of the dragging
        GEvent.addListener(mark, 'dragend', function() {
          // set the new position to the one at the end of the dragging
          formSetPosition(form, this.getPoint());
        });
      }
    }
  });
}


/*
 * send an query to the server to get the infomation about the specified demonstration
 * the answer will be treated by showDemonstration
 */
/* void */ function loadDemonstration(/* Gmap */ gmap, /* String */ id) {
  GDownloadUrl('getDemonstration.php?id=' + id + "&withUsers=1", function(text) {
    showDemonstration(gmap, id, text, true);
  });
}

/*
 * send an query to the server to get all the infomation about all the demonstrations
 * the answer will be treated by showDemonstration
 */
/* void */ function loadDemonstrations(gmap) {
  GDownloadUrl('getDemonstration.php?withUsers=1', function(text) {
    showDemonstrations(gmap, text);
  });
}

/*
 * Create a marker for a participant and his info window
 * return the newly created marker
 */
/* GMarker */ function createParticipantMarker(/* Gmap */ gmap,  /* Json result, the participant node */ p){

  // we were cloning it before but it's not needed since we always use the exact same icon
  // clone the default icon create earlier
  //var icon = new GIcon(baseIconParticipant);
  
  // create a point based on the latitude and longitude of the participant
  var point = new GLatLng(p.latitude, p.longitude);

  // create the marker with the icons and position
  // create a new member to the participant object to store the marker
  p.marker = new GMarker(point, baseIconParticipant);

  // add a function to the participant object for displaying the infoWindow
  p.show=function() {
    p.marker.openInfoWindowHtml("<b>" + p.title + "</b><br />	"+p.personaltext);
  };
  // add the p.show function to click listener on the marker
  GEvent.addListener(p.marker, "click", p.show);

  // add the marker to the map
  gmap.addOverlay(p.marker); 
  return p.marker;
}

/*
 * show the info window of a participant
 * 
 */
/* void */ function selectParticipant(/* String */ id){
  // go over all the participants to find the specified one
  for (var i = 0; i < participantData.points.length ; ++i) {
    if (participantData.points[i].id==id) {
      // show his info window
      participantData.points[i].show();
      return ;
    }
  }
}

/*
 * show the info window of a demonstration
 * 
 */
function selectDemonstration(id){
  // go over all the demonstrations to find the specified one
  for (var i = 0; i < demonstrationsData.demonstration.length ; ++i) {
    var demo = demonstrationsData.demonstration[i];
    if (demo.id==id) {
      // show his info window
      demo.show();
    }
  }
    
}

/*
 * Create a marker for a Demonstration and his info window
 * return the newly created marker
 */
/* GMarker */ function createDemonstrationMarker(/* Gmap */ gmap,  /* Json result, the demonstration node */ p){

  // create a point based on the latitude and longitude of the demonstration
  var point = new GLatLng(p.latitude, p.longitude);

  // create the marker with the icons and position
  // create a new member to the demonstration object to store the marker
  p.marker = new GMarker(point, baseIconDemonstration);

  // add a function to the demonstration object for displaying the infoWindow
  p.show=function() {
    p.marker.openInfoWindowHtml("<b>" + p.title + "</b><br />	"+p.description+"<br /><a href=\"?id=" + p.id + "\">plus</a>");
  };
  // add the p.show function to click listener on the marker
  GEvent.addListener(p.marker, "click", p.show);

  // add the marker to the map
  gmap.addOverlay(p.marker); 
  return p.marker;
}

/*
 * display all the demonstrations
 * 
 */
/* void */ function showDemonstrations(/* Gmap */ gmap, /* json as text */ text) {
  // evaluate the json to create javascript objects.
  demonstrationsData = eval('[' + text + '][0]');

  // go over all the demonstrations to find the specified one
 for (var i = 0; i < demonstrationsData.demonstration.length; i++)
 {
    var demo = demonstrationsData.demonstration[i];
    // create the html to display the informations about a demonstration
    $('demonstration_list').innerHTML = $('demonstration_list').innerHTML  + "<div class=\"demonstration\"><div class=\"demonstration_title\"><a href='javascript:selectDemonstration(\""+demo.id+"\");'>" + demo.title + "</a></div><div class=\"demonstration_desc\">" + demo.description + "</div></div>";
     // add the demonstration to the map
     createDemonstrationMarker(gmap, demo);
  }
}

/*
 * display a demonstration and it's participants
 * 
 */
/* void */ function showDemonstration(/* Gmap */gmap, /* String */ id, /* json as text */ text) {
  // evaluate the json to create javascript objects.
  participantData = eval('[' + text + '][0]');
  if (participantData.demonstration && participantData.demonstration.length > 0) {
    var demo = participantData.demonstration[0];
    // set informations about the demonstration
    $('demonstration_title').innerHTML = demo.title;
    $('demonstration_description').innerHTML = demo.description;
    $('demo_info').style.display = '';

    //center the map to the demonstration
    gmap.setCenter(new GLatLng(demo.latitude, demo.longitude), 12);
    // add the marker of the demonstration
    createDemonstrationMarker(gmap,demo);
  }

  if (participantData.points && participantData.points.length > 0) {
    // go over all the participants
    for (var i = 0; i < participantData.points.length; ++i) {
      var p = participantData.points[i];
        // add the participant to the map
	createParticipantMarker(gmap,p);
        // add the participant in the participant list
	$('participants').innerHTML+="<li><a href='javascript:selectParticipant(\""+p.id+"\");'>"+p.title+"</a></li>"; 
    }
  } 
  // if the user has not already participated to the demonstration,  we show the form and activate the position marker.
  if (!participant) {
    $('saveparticipant').elements['manifestation_id'].value = id;
    addPositionMarker(gmap, 'saveparticipant');
  }
}

/**
 * set the position in the form
 * @param form : the id of the form
 * @param pos : a GLatLng with the position of the selected point
 */
/* void */ function formSetPosition(/* String */ form, /* GLatLng */ pos) {
  $(form).elements['latitude'].value = pos.lat();
  $(form).elements['longitude'].value = pos.lng();
}

/*
 * verify if the demonstration position is set
 *
 */
/* boolean */ function checkCreate() {
  if (!$('lat').value || !$('lng').value) {
    alert('you need a start point');
    return false;
  }
  return true;
}

/*
 * verify if the participant's position is set
 *
 */
/* boolean */ function checkCreateParticpant() {
  if (!$('lat2').value || !$('lng2').value) {
    alert('you need a start point');
    return false;
  }
  return true;
}

/**
 * DEBUG
 *
 */
function debug(chapter,text){
	$('debug').innerHTML+=	$('debug').innerHTML+ "<br><b>"+chapter+"</b>"+text	;
}


/**
 * Cookies management
 *
 */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
